package com.zhb.scanner.utils

import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.zhb.tools.ZLog
import java.util.*

/**
 * Created by HongboZhao on 2020/12/30.
 */
object KeyboardTools {
    @JvmStatic
    fun showKeyboard(view: View?) {
        if (view == null) {
            return
        }
        val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED)
    }

    @JvmStatic
    fun hideKeyboard(view: View?) {
        if (view == null) {
            return
        }
        try {
            val imm =
                view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (imm.isActive) {
                imm.hideSoftInputFromWindow(view.applicationWindowToken, 0) //强制隐藏键盘
            }
        } catch (e: Exception) {
            ZLog.e("关闭键盘错误", e)
        }
    }

    //通过定时器强制打开虚拟键盘
    fun timerShowKeyboard(view: View?) {
        if (view == null) {
            return
        }
        val timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                val imm =
                    view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                if (!imm.isActive(view)) {
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
                }
            }
        }, 10)
    }
}